package com.skit.main.activity

import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.animation.AlphaAnimation
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.google.gson.Gson
import com.skit.common.base.BaseActivity
import com.skit.common.bean.ActivityBean
import com.skit.common.config.RouteConfig
import com.skit.common.event.EventMessage
import com.skit.common.http.HttpUtils
import com.skit.common.ktx.RetrofitKtx.getService
import com.skit.common.ktx.setSupportActionBar
import com.skit.common.manager.UserManager
import com.skit.common.utils.StatusUtils
import com.skit.common.utils.ToastUtils
import com.skit.main.R
import com.skit.main.adapter.MainBannerAdapter
import com.skit.main.databinding.MainActivityDetailsBinding
import com.skit.main.fragment.ActivityInfoFragment
import com.skit.main.fragment.ActivityTypeInfoFragment
import com.skit.common.retrofit.ActivityProtocol
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.EventBus
import retrofit2.Retrofit
import javax.inject.Inject

/**
 * @author shuike <a href="mailto:shuike007@gmail.com">Contact me.</a>
 * @version 1.0
 * @since  2020/5/19
 */

@AndroidEntryPoint
@Route(path = RouteConfig.MainRoute.MAIN_ACTIVITY_DETAILS)
class ActivityDetailsActivity : BaseActivity() {

    companion object {
        const val TAG = "ActivityDetailsActivity"

        enum class State {
            EXPANDED,
            COLLAPSED,
            IDLE
        }
    }

    private lateinit var binding: MainActivityDetailsBinding
    private lateinit var activityInfoFragment: ActivityInfoFragment
    private var bannerIsStop: Boolean = false
    private val titles = arrayOf("活动信息", "学分相关")

    @JvmField
    @Autowired(name = "bean")
    var activityBean: ActivityBean? = null

    @JvmField
    @Autowired(name = "admin")
    var admin: Boolean? = false

    @Inject
    lateinit var retrofit: Retrofit

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
        binding = MainActivityDetailsBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.toolbar.setSupportActionBar()
        if (activityBean == null) {
            finish()
            return
        }
        initViews()
        intData()
        getData()
    }

    private fun initViews() {
        binding.toolbar.overflowIcon =
            ContextCompat.getDrawable(this, R.drawable.ic_more_vert_black_24dp)

        title = activityBean?.activityName
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        val bannerAdapter =
            MainBannerAdapter(activityBean?.activityImages as MutableList<String>, true)
        binding.banner.adapter = bannerAdapter

        var state: State = State.IDLE
        val alphaAnimation = AlphaAnimation(1F, 0F)
        alphaAnimation.duration = 1000
        activityInfoFragment = ActivityInfoFragment.newInstances(activityBean!!)
        val activityTypeFragment = ActivityTypeInfoFragment.newInstances(activityBean!!)
        val fragments: Array<Fragment> = arrayOf(activityInfoFragment, activityTypeFragment)

        binding.apply {
            appbar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
                if (verticalOffset == 0) {
                    refreshLayout.isEnabled = true
                    if (state != State.EXPANDED) state = State.EXPANDED
                    banner.start()
                    bannerIsStop = false
                } else if (!bannerIsStop) {
                    refreshLayout.isEnabled = false

                    if (state != State.IDLE) state = State.IDLE
                    banner.stop()
                    bannerIsStop = true
                }
            })
            viewPager2.adapter = FragmentAdapter(fragments, this@ActivityDetailsActivity)
            TabLayoutMediator(tabLayout, viewPager2) { tab, position ->
                tab.text = titles[position]
            }.attach()
            refreshLayout.setOnRefreshListener { getData() }
        }
    }

    private fun getData() {
        val user = UserManager.user
        val activityProtocol: ActivityProtocol =
            retrofit.getService(ActivityProtocol::class.java)
        Log.d(TAG, "getData: ${activityBean!!.id}")
        val activityInfo =
            activityProtocol.getActivityInfo(activityBean!!.id, user?.id ?: 0)
        HttpUtils.doRequest(activityInfo) {
            binding.refreshLayout.isRefreshing = false
            if (it == null) {
                ToastUtils.showToast("请求失败")
                return@doRequest
            }

            if (it.isSuccess) {
                activityBean = it.data
                intData()
                invalidateOptionsMenu()
                activityInfoFragment.data(activityBean!!)
            }
        }
    }

    private fun intData() {
        if (admin != null && admin!!) {
            activityBean?.let {
                binding.apply {
                    applyBt.text = StatusUtils.statusText(it.status)
                    applyBt.setBackgroundColor(
                        StatusUtils.statusColor(
                            applicationContext,
                            it.status
                        )
                    )
                }
            }

            binding.applyBt.setOnClickListener {
                val arrayOf = arrayOf("待审核", "同意发布", "拒绝发布")
                val alertDialog = AlertDialog.Builder(this).setItems(arrayOf) { dialog, which ->
                    run {
                        val user = UserManager.user
                        if (user != null) {
                            val service =
                                retrofit.getService(ActivityProtocol::class.java)
                            val call =
                                service.changeStatus(user.token, user.id, activityBean!!.id, which)
                            HttpUtils.doRequest(call) {
                                if (it == null || !it.isSuccess) {
                                    if (it != null) ToastUtils.showToast(it.msg)
                                    return@doRequest
                                }
                                ToastUtils.showToast("已更改状态")
                                val statusColor = StatusUtils.statusColor(applicationContext, which)
                                binding.apply {
                                    applyBt.setBackgroundColor(statusColor)
                                    applyBt.text = StatusUtils.statusText(which)
                                }
                            }
                        } else {
                            ToastUtils.showToast("未登录")
                        }

                    }
                }
                alertDialog.show()
            }
            return
        }

        if (UserManager.user == null) {
            binding.apply {
                applyBt.isClickable = false
                applyBt.text = "未登录"
                applyBt.setBackgroundColor(ContextCompat.getColor(applicationContext, R.color.gray))
            }
            return
        }

        if (UserManager.user!!.userInfo.department == null) {
            binding.apply {
                applyBt.isClickable = false
                applyBt.text = "资料未完善"
                applyBt.setBackgroundColor(ContextCompat.getColor(applicationContext, R.color.gray))
            }
            return
        }

        if (UserManager.user != null) {
            binding.applyBt.setOnClickListener {
                if (UserManager.user!!.id == activityBean!!.founderID || activityBean!!.applyStatus == 3) {
                    ManageActivity.startActivity(this, activityBean)
                } else {
                    applyDialog()
                }

            }
        }

        when (activityBean!!.range) {
            0 -> {
                binding.applyBt.isClickable = true
            }
            1 -> {
                val campus = UserManager.user?.userInfo?.department?.campus
                binding.applyBt.isClickable =
                    campus != null && campus == activityBean?.organizer?.campus
            }
            2 -> {
                val id = UserManager.user?.userInfo?.department?.id
                binding.applyBt.isClickable = id != null && id == activityBean?.organizerID
            }
            3 -> {
                val id = UserManager.user?.userInfo?.department?.id
                binding.applyBt.isClickable = id != null && id == activityBean?.organizerID
            }
        }


        binding.apply {
            if (!applyBt.isClickable) {
                applyBt.text = "您不在报名范围内"
                applyBt.setBackgroundColor(
                    ContextCompat.getColor(
                        this@ActivityDetailsActivity,
                        R.color.gray
                    )
                )
            }
        }


        if (activityBean!!.signUpEndTime < System.currentTimeMillis()) {
            binding.apply {
                applyBt.isClickable = false
                applyBt.text = "报名已截止"
                applyBt.setBackgroundColor(
                    ContextCompat.getColor(
                        this@ActivityDetailsActivity,
                        R.color.gray
                    )
                )
            }
        }


        if (activityBean!!.endTime < System.currentTimeMillis()) {
            binding.apply {
                applyBt.isClickable = false
                applyBt.text = "活动已结束"
                applyBt.setBackgroundColor(
                    ContextCompat.getColor(
                        this@ActivityDetailsActivity,
                        R.color.gray
                    )
                )
            }
        }


        if (UserManager.user != null && UserManager.user!!.id == activityBean!!.founderID) {

            binding.apply {
                applyBt.text = "管理活动"
                applyBt.isClickable = true
                applyBt.setBackgroundResource(R.drawable.apply_bt_bg)
            }
        } else {
            when (activityBean!!.applyStatus) {
                -1 -> {

                }
                0 -> {

                    binding.apply {
                        applyBt.isClickable = false
                        applyBt.text = "审核中"
                        applyBt.setBackgroundColor(
                            ContextCompat.getColor(
                                applicationContext,
                                R.color.gray
                            )
                        )
                    }
                }
                1 -> {

                    binding.apply {
                        applyBt.isClickable = false
                        applyBt.text = "审核未通过"
                        applyBt.setBackgroundColor(
                            ContextCompat.getColor(
                                applicationContext,
                                R.color.gray
                            )
                        )
                    }
                }
                2 -> {

                    binding.apply {
                        applyBt.isClickable = false
                        applyBt.text = "审核已通过"
                        applyBt.setBackgroundColor(
                            ContextCompat.getColor(
                                applicationContext,
                                R.color.blue
                            )
                        )
                    }
                }
                3 -> {

                    binding.apply {
                        applyBt.text = "管理活动"
                        applyBt.isClickable = true
                        applyBt.setBackgroundResource(R.drawable.apply_bt_bg)
                    }
                }
            }
        }
    }

    private fun applyDialog() {
        val user = UserManager.user!!
        AlertDialog.Builder(this).setTitle("报名活动").setMessage("是否确认报名申请？")
            .setPositiveButton("确认") { _, _ ->
                run {
                    val map: MutableMap<String, Any> = HashMap()
                    map["uid"] = user.id
                    map["aid"] = activityBean!!.id

                    val service =
                        retrofit.getService(ActivityProtocol::class.java)
                    val call =
                        service.apply(user.token, Gson().toJson(map))
                    HttpUtils.doRequest(call) {
                        if (it == null || !it.isSuccess) {
                            if (it != null) ToastUtils.showToast(it.msg)
                            return@doRequest
                        }
                        ToastUtils.showToast("申请成功")
                        activityBean!!.applyStatus = 0
                        intData()
                    }
                }
            }.setNegativeButton("取消", null)
            .show()
    }

    class FragmentAdapter(private val array: Array<Fragment>, fragmentActivity: FragmentActivity) :
        FragmentStateAdapter(
            fragmentActivity
        ) {
        override fun getItemCount(): Int = array.size

        override fun createFragment(position: Int): Fragment = array[position]

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == 0) {
            val user = UserManager.user ?: return false
            activityBean?.also { bean ->
                val create = retrofit.create(ActivityProtocol::class.java)
                val addType = if (bean.isCollect) "cancel" else "add"
                val call =
                    create.addCollect(user.id, bean.id, addType)
                HttpUtils.doRequest(call) {
                    if (it != null && it.isSuccess) {
                        ToastUtils.showToast(it.msg)
                        val isCollect = addType == "add"
                        activityBean?.isCollect = isCollect
                        EventBus.getDefault().post(
                            EventMessage(
                                if (isCollect) EventMessage.MessageCode.ADD_ACTIVITY_COLLECT else
                                    EventMessage.MessageCode.CANCEl_ACTIVITY_COLLECT, bean
                            )
                        )
                        invalidateOptionsMenu()
                    } else {
                        it?.let {
                            ToastUtils.showToast(it.msg)
                        }
                    }
                }
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
        menu?.apply {
            clear()
            activityBean?.also { bean ->
                add(0, 0, 0, if (bean.isCollect) "取消收藏" else "收藏").apply {
                    icon = ContextCompat.getDrawable(
                        this@ActivityDetailsActivity,
                        if (bean.isCollect) {
                            R.drawable.ic_round_star_24//已收藏
                        } else {
                            R.drawable.ic_round_star_border_24//未收藏
                        }
                    )
                    setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
                }
            }
            add(0, 1, 1, "活动人员").apply {
                icon = ContextCompat.getDrawable(
                    this@ActivityDetailsActivity,
                    R.drawable.ic_people_black_24dp
                )
                setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
            }
            add(0, 2, 2, "分享")
        }
        return super.onPrepareOptionsMenu(menu)
    }
}